package com.lemon.components.ant.project.makeservice.beanparser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import lombok.Builder;
import lombok.Data;

public class RemarkGetter {

	@Builder
	@Data
	public static class ColumnIndex{
		
		private int codeIndex;
		private int remarkIndex;
		private int reqiredIndex;
		
	}
	
	@Data
	public static class RemarkInfo{
		private String code;
		private String remark;
		private boolean reqired;
	}
	
	public static void main(String[] args) {
		RemarkGetter remarkGetter = new RemarkGetter();
		String url = "https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1";
		String cssQueryString = "table.table tbody tr";
		String cssColumnString="td";
		remarkGetter.remarks(url,cssQueryString,cssColumnString,
				ColumnIndex.builder().codeIndex(1).remarkIndex(0).reqiredIndex(2).build());
		System.out.println(remarkGetter.toString());
	}
	
	public Document getDocument(String url, Map<String, String> cookies) {
		try {
			Connection con = Jsoup.connect(url);
			if (cookies != null) {
				con = con.cookies(cookies);
			}
			Document document = con.userAgent(
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36")
					.timeout(30000).ignoreContentType(true).ignoreHttpErrors(true).get();
			return document;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	private List<RemarkInfo> list;
	
	public List<RemarkInfo> remarks(String url,String cssQuery,String cssColumnQuery,ColumnIndex columnIndex){
		
		Document rootDocument = getDocument(url,null);
		
		Elements elements = rootDocument.select(cssQuery);
		list = new ArrayList<>();
		elements.forEach(item -> {
			Elements tmp = item.select(cssColumnQuery);
			RemarkInfo remarkInfo = new RemarkInfo();
			if (tmp.get(columnIndex.getCodeIndex()).hasText()) {
				remarkInfo.setCode(tmp.get(columnIndex.getCodeIndex()).text().trim());
			}
			if (tmp.get(columnIndex.getRemarkIndex()).hasText()) {
				remarkInfo.setRemark(tmp.get(columnIndex.getRemarkIndex()).text().trim());
			}
			if (tmp.get(columnIndex.getReqiredIndex()).hasText()) {
				if (tmp.get(columnIndex.getReqiredIndex()).text().trim().equals("是")) {
					remarkInfo.setReqired(true);
				}
			}
			list.add(remarkInfo);
		});
		
		return list;
	}
	
	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		if (list != null) {
			list.forEach(item -> {
				stringBuilder.append(item.getCode());
				stringBuilder.append("\t");
				stringBuilder.append(item.getRemark());
				stringBuilder.append("\t");
				stringBuilder.append(item.isReqired());
				stringBuilder.append("\n");
			});
		}
		return stringBuilder.toString();
	}
}
